package com.moji.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.moji.config.AlipayConfig;
import com.moji.entity.MjOrder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

@Service

public class AlipayService {
    @Autowired
    private AlipayConfig alipayConfig;

    public String pay(MjOrder order) throws Exception {
        //获取要向支付宝支付的参数,由页面传过来
        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = order.getOrderCode();
        //付款金额，必填
        String total_amount = order.getOrderAmount().setScale(2, BigDecimal.ROUND_HALF_UP)+"";
//        String total_amount = "0.01";
        String subject = "付款";
        //商品描述，可空
        String body = "";
        //获得初始化的AlipayClient
        String alipayGateWay = AlipayConfig.getAlipayGateWay();
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.getAlipayGateWay(),
                alipayConfig.getAppId(), alipayConfig.getPrivateKey(),
                "json", "UTF-8", alipayConfig.getPublicKey(), "RSA2");
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(alipayConfig.getReturnUrl()+order.getId());  //设置同步回调通知
        alipayRequest.setNotifyUrl(alipayConfig.getPayCallbackUrl());  //设置异步回调通知
        //设置支付参数
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("out_trade_no", out_trade_no);
        paramMap.put("total_amount", total_amount);
        paramMap.put("subject", subject);
        paramMap.put("body", body);
        paramMap.put("product_code", "FAST_INSTANT_TRADE_PAY");
        alipayRequest.setBizContent(JSON.toJSONString(paramMap));

//        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
//                + "\"total_amount\":\"" + total_amount + "\","
//                + "\"subject\":\"" + subject + "\","
//                + "\"body\":\"" + body + "\","
//                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求
        String result = null;
        String apiUrl = null;
        try {
            AlipayTradePagePayResponse post = alipayClient.pageExecute(alipayRequest, "POST");
            String code = post.getCode();
            result = post.getBody();
//            result = alipayClient.sdkExecute(alipayRequest).getBody();
//            apiUrl=AlipayConfig.getAlipayGateWay()+"?"+result;
//            log.info("------------#####################-------------result={}", result);
        } catch (AlipayApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 微信统一下单方法 生成用户扫码支付的二维码的URL
     * https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=9_1
     * 除付款码支付场景以外，商户系统先调用该接口在微信支付服务后台生成预支付交易单，返回正确的预支付交易会话标识后再按Native、JSAPI、APP等不同场景生成交易串调起支付。
     *
     * @return
     */

    private String getParamStr(Map<String, String> map) {
        ArrayList list = new ArrayList();
        for (Map.Entry entry : map.entrySet()) {
            if (entry.getValue() != "") {
                list.add(new StringBuilder().append((String) entry.getKey()).append("=").append((String) entry.getValue()).append("&").toString());
            }
        }
        int size = list.size();
        String[] arrayToSort = (String[]) list.toArray(new String[size]);
        Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < size; i++) {
            sb.append(arrayToSort[i]);
        }
        String result = "";
        if (sb.length() > 0)
            result = sb.subSequence(0, sb.length() - 1).toString();
        else {
            result = sb.toString();
        }
        return result;
    }

    public static void main(String[] args) {
        // 配置参数
        String serverUrl = "https://openapi.alipay.com/gateway.do";
        String appId = "2021004144614528";
        String privateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCAyDREmk7/M2in55QdPNq9ScayBuw2xdVPqVvM9a7BLqB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qT0lEgMVudp2fVazHe+6xpYadqt+PznktvzfTymT4yT373aPMkWocTNYcfKCU2ftVQ7SXdjdOdXcdabxfmn4bTDaYVKT3JIQKBgATSJpuCaOq8RhZHXBaCjU06yMcrFQ8k1bCtP1WRQ7VmnWrgX94I92S0sKBTqqGEUylNHw5pLlFFPKkKmLKS4GBryK+10IChNmzR8SxZ3RHL85Jm8/vPJt0lwqznYsIgHtF2q9JnOJhkwBLSYp8yDMh4jeTGI7dCI6TY9USNKhiVAoGAah42L2aU0dVV52JY/iMS+FhTaVBd8FffEpot6x/mjFYYdXThenNoi3kvD0/nguRQHLHzupvrao5NOHkq1YUkDUg4ZUn6HvxiL9TiHOWCztRIG8CyBwKTtulDiFO03VVEIyDCTAQjZUS3u9uRpdJEbcwGBpuAOqBCECY5vycHeaw=";
        String format = "json";
        String charset = "UTF-8";
        String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgMg0RJpO/zNop+eUHTzavUnGsgbsNsXVT6lbzPWuwS6geP9zAWuDl/OAPCWq3lGleMhVIOaTiGOLxZlzgh72HudRw6/xqZU5xd62hSHs+m5JLZC+jcKgTK5x788Penf7vgso0Tomwp8M8iPcSLOY16xQe3pwuFwyQe4EyScu0oInbE/dEKlkk89lhprIKBUSFnjPCQSPA/TaDQCELDF1dDDNTC1eEPCWhzjBGKVMhROzFzyLBJj8+iB+xTwizr4PGGB/QkzcLEGoW9C20WaV2saHYVKOmqTGfi28lYuEJPg7B3vktttAbD7vbZjf4CQG5pkrC85MPZh9m/dtu7PA/QIDAQAB";
        String signType = "RSA2";

        // 使用SDK生成二维码
        AlipayClient alipayClient = new DefaultAlipayClient(serverUrl, appId, privateKey, format, charset, alipayPublicKey, signType);

        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        QrCode qrCode = new QrCode();
        qrCode.setQrCode("二维码内容");
        request.setBizModel(qrCode);

        try {
            AlipayTradePrecreateResponse response = alipayClient.execute(request);
            if(response.isSuccess()){
                System.out.println("二维码生成成功: " + response.getQrCode());
            } else {
                System.out.println("二维码生成失败: " + response.getSubCode() + " - " + response.getSubMsg());
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
    }
}
